package com.weiyuwqj.server.service.invest.module;

import com.weiyuwqj.api.constant.ItemStatus;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.constant.OperateContants;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.exception.HfException;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
//import com.weiyuwqj.api.hengfeng.param.vo.HfBidRepayVo;
import com.weiyuwqj.api.model.BasItem;
import com.weiyuwqj.api.model.BasUser;
import com.weiyuwqj.api.model.BusAccount;
import com.weiyuwqj.api.model.BusIncome;
import com.weiyuwqj.api.model.BusItemInvest;
import com.weiyuwqj.api.model.BusItemRepay;
import com.weiyuwqj.api.model.BusRepayOrder;
import com.weiyuwqj.api.model.BusVerifyLog;
import com.weiyuwqj.api.model.vo.RepayCollectVo;
import com.weiyuwqj.api.service.BusAutoInvestService;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.StringUtils;
import com.weiyuwqj.server.mapper.BasItemMapper;
import com.weiyuwqj.server.mapper.BasItemPrepaymentMapper;
import com.weiyuwqj.server.mapper.BasUserMapper;
import com.weiyuwqj.server.mapper.BusAccountMapper;
import com.weiyuwqj.server.mapper.BusDebtCollectMapper;
import com.weiyuwqj.server.mapper.BusIncomeMapper;
import com.weiyuwqj.server.mapper.BusIncomeStatMapper;
import com.weiyuwqj.server.mapper.BusItemAutoSortMapper;
import com.weiyuwqj.server.mapper.BusItemCollectMapper;
import com.weiyuwqj.server.mapper.BusItemInvestMapper;
import com.weiyuwqj.server.mapper.BusItemRepayMapper;
import com.weiyuwqj.server.mapper.BusRepayOrderMapper;
import com.weiyuwqj.server.mapper.BusVerifyLogMapper;
import com.weiyuwqj.server.mapper.SysNoticeMapper;
import com.weiyuwqj.server.mapper.SysNoticeTypeMapper;
//import com.weiyuwqj.server.pay.InvestApi;
import com.weiyuwqj.server.service.account.module.DealAction;
import com.weiyuwqj.server.service.account.module.DealModule;
import com.weiyuwqj.server.service.account.module.action.user.invest.ReceiveRepayCashDealAction;
import com.weiyuwqj.server.service.account.module.action.user.invest.RepayDealAction;
import com.weiyuwqj.server.service.finance.module.OperateModule;
import com.weiyuwqj.server.service.finance.module.action.ExpendOperateAction;
import com.weiyuwqj.server.service.finance.module.action.IncomeOperateAction;
import com.weiyuwqj.server.service.finance.module.action.OperateAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyong on 2016/8/12.
 */
@Component
public class RepayModule {

    @Autowired
    BusItemRepayMapper itemRepayMapper;

    @Autowired
    BusItemCollectMapper itemCollectMapper;

    @Autowired
    DealModule dealModule;

    @Autowired
    BasItemMapper itemMapper;

    @Autowired
    BusItemInvestMapper itemInvestMapper;

    @Autowired
    BusIncomeMapper incomeMapper;

    @Autowired
    BusIncomeStatMapper incomeStatMapper;

    @Autowired
    BasUserMapper userMapper;

    @Autowired
    SysNoticeMapper noticeMapper;

    @Autowired
    SysNoticeTypeMapper noticeTypeMapper;

    @Autowired
    BusVerifyLogMapper verifyLogMapper;

    @Autowired
    BasItemPrepaymentMapper itemPrepaymentMapper;

    @Autowired
    BusAccountMapper accountMapper;

    @Autowired
    BusRepayOrderMapper repayOrderMapper;


    @Autowired
    BusAutoInvestService autoInvestService;

    @Autowired
    BusItemRepayMapper repayMapper;

    @Autowired
    private BusItemCollectMapper collectMapper;

    @Autowired
    BusDebtCollectMapper debtCollectMapper;

    @Autowired
    BusItemInvestMapper investMapper;

    @Autowired
    BusItemAutoSortMapper itemAutoSortMapper;
    @Autowired
    private OperateModule operateModule;

//
//    @Autowired
//    InvestApi investApi;


//    //借款人还款
//    public Map borrowerRepay(Integer itemId, Integer currentPeriod){
//
//        //判断还款计划状态
//        BasItem item = itemMapper.selectByPrimaryKey(itemId);
//        BasUser user=userMapper.selectByPrimaryKey(item.getItemUserId());
//        BusItemRepay itemRepay = repayMapper.getRepayListByItemIdAndCurrentPeriod(itemId, currentPeriod);
//        if (itemRepay == null) {
//            throw new CrowdException("item.repay.not_found");
//        } else if (itemRepay.getStatus() != 0) {
//            throw new CrowdException("item.repay.status_not_correct");
//        }
//
//        itemRepay.setActualRepayAmount(itemRepay.getRepayAmount());
//        itemRepay.setActualRepayPrincipal(itemRepay.getRepayPrincipal());
//        itemRepay.setActualRepayInterest(itemRepay.getRepayInterest());
//        itemRepay.setStatus(1);
//        itemRepay.setActualRepayTime(new Date());
//        itemRepay.setPlatformId(user.getPlatformId());
//
//
//        //检查账户情况
//        BusAccount account = accountMapper.getBusAccountByUserId(item.getItemUserId());
//        BigDecimal repayAmount = itemRepay.getRepayAmount();
//        if (account.getUsable().compareTo(repayAmount) == -1) {
//            throw new CrowdException("item.repay.balance_is_not_enough");
//        }
//        //更新标账户余额
//        int count = itemMapper.updateUsableById(item.getUsable(),itemRepay.getActualRepayAmount(),itemId);
//        if(count < 1){
//            throw new CrowdException("update_error");
//        }
//        //处理借款人账户
//        DealAction repayAction = new RepayDealAction();
//        repayAction.deal(item.getItemUserId(), itemRepay.getActualRepayAmount(), "支付" + item.getItemName() + "项目本息");
//        count = dealModule.dealAction(repayAction);
//        if (count < 1) {
//            throw new CrowdException("update_error");
//        }
//        //插入资金明细记录
//        OperateAction operate = new ExpendOperateAction();
//        operate.operateAction(itemRepay.getOrderNo(), OperateContants.BORROWER_REPAY,itemId,
//                item.getItemName(),itemRepay.getRepayAmount());
//        operateModule.operateAction(operate);
//
//        //更新标的状态
//        if(itemRepay.getRepayCurrentPeriod() == 1){
//            itemMapper.updateItemStatus(ItemStatus.REPAYING, ItemStatus.REPAY_COMPLETE, itemRepay.getItemId());
//        }else if (itemRepay.getRepayCurrentPeriod().intValue() == itemRepay.getRepayTotalPeriod().intValue()) {
//            itemMapper.updateItemStatus(ItemStatus.REPAY_PART, ItemStatus.REPAY_COMPLETE, itemRepay.getItemId());
//        } else {
//            itemMapper.updateItemStatus(ItemStatus.REPAYING, ItemStatus.REPAY_PART, itemRepay.getItemId());
//        }
//
//        //更新repay
//        count = repayMapper.updateRepayStatus(itemRepay);
//        if(count < 1){
//            throw new CrowdException("update_error");
//        }
//
//        //添加日志，还款的类型5
//        BusVerifyLog log = new BusVerifyLog();
//        log.setOperateUserId(1);
//        log.setContent("借款人项目还款：" + item.getItemName());
//        log.setAddtime(new Date());
//        log.setType((byte) 5);
//        log.setItemId(itemRepay.getItemId());
//        log.setStatus((byte) 1);
//        log.setAddip(IpUtils.get());
//        verifyLogMapper.insert(log);
//
//        List<BusItemRepay> itemRepays = new ArrayList<BusItemRepay>();
//        itemRepays.add(itemRepay);
//
//        HfResultBean result = investApi.borrowRepay(itemRepays);
//        if (result.isSuccess()) {
//            //if(!result.get("success_num").equals(result.get("total_num"))){
//            //    //失败原因
//            //    List<HashMap> list = (ArrayList)result.get("error_data");
//            //    final StringBuffer errorData = new StringBuffer("");
//            //    for (Map errorMap:list){
//            //        String failInfo = errorMap.get("error_info").toString();
//            //        errorData.append(failInfo+",");
//            //    }
//            //    throw new XfException("HfException",errorData.toString());
//            //}
//            return Message.OK;
//        }else {
//            throw new HfException("HfException", result.getMessageText());
//        }
//    }

//    //标账户还款给投资人
//    public Map itemRepay(Integer itemId, Integer currentPeriod) {
//
//        //判断还款计划状态
//        BasItem item = itemMapper.selectByPrimaryKey(itemId);
//
//        BusItemRepay itemRepay = repayMapper.getRepayListByItemIdAndCurrentPeriod(itemId, currentPeriod);
//        if (itemRepay == null) {
//            throw new CrowdException("item.repay.not_found");
//        } else if (itemRepay.getStatus() != 1) {
//            throw new CrowdException("item.repay.status_not_correct");
//        }
//
//        //检查标的账户金额
//        BigDecimal repayAmount = itemRepay.getActualRepayAmount();
//        if (item.getUsable().compareTo(repayAmount) == -1) {
//            throw new CrowdException("item.repay.balance_is_not_enough");
//        }
//
//        //查询项目待收计划和债权待收计划
//        List<RepayCollectVo> itemCollects = collectMapper.listUsefulCollect(itemId, currentPeriod);
//        List<RepayCollectVo> debtCollects = debtCollectMapper.listUsefulCollect(itemId, currentPeriod);
//        itemCollects.addAll(debtCollects);
//        BigDecimal totalCollectAmount = BigDecimal.ZERO;
//        BigDecimal totalCollectPrincipal = BigDecimal.ZERO;
//        BigDecimal totalCollectInterest = BigDecimal.ZERO;
//        int count;
//        for (RepayCollectVo repayCollectVo : itemCollects) {
//
//            //处理投资人待收
//            Map map = new HashMap();
//            map.put("collectAmount", repayCollectVo.getCollectAmount());
//            map.put("collectPrincipal", repayCollectVo.getCollectPrincipal());
//            map.put("collectInterest", repayCollectVo.getCollectInterest());
//            map.put("collectTime", new Date());
//            map.put("collectStatus", 1);
//            map.put("id", repayCollectVo.getId());
//            map.put("userId", repayCollectVo.getInvestUserId());
//            if ("item".equals(repayCollectVo.getType())) {
//                collectMapper.updateActualCollect(map);
//            } else {
//                debtCollectMapper.updateActualCollect(map);
//            }
//
//            repayCollectVo.setActualCollectAmount(repayCollectVo.getCollectAmount());
//            repayCollectVo.setActualCollectPrincipal(repayCollectVo.getCollectPrincipal());
//            repayCollectVo.setActualCollectInterest(repayCollectVo.getCollectInterest());
//            repayCollectVo.setActualCollectTime(new Date());
//
//            //统计还款总额
//            totalCollectAmount = totalCollectAmount.add(repayCollectVo.getCollectAmount().
//                    subtract(repayCollectVo.getAdditionalRateAmount()));
//            totalCollectPrincipal = totalCollectPrincipal.add(repayCollectVo.getCollectPrincipal());
//            totalCollectInterest = totalCollectInterest.add(repayCollectVo.getCollectInterest().
//                    subtract(repayCollectVo.getAdditionalRateAmount()));
//
//            //更新invest表
//            if (repayCollectVo.getCollectTotalPeriod().intValue() == repayCollectVo.getCollectCurrentPeriod().intValue()) {
//                investMapper.updateItemInvestStatus(1, 3, repayCollectVo.getInvestId());
//            }
//
//            //更新投资表,暂时这样写，有可能因为mysql隔离机制导致报错
//            BusItemInvest invest = investMapper.selectByPrimaryKey(repayCollectVo.getInvestId());
//            investMapper.updateItemRepayInvestCollet(invest.getCollectPrincipal().add(repayCollectVo.getCollectPrincipal()),
//                    invest.getCollectInterest().add(repayCollectVo.getCollectInterest()),
//                    repayCollectVo.getInvestId());
//
//            //添加收益
//            this.addIncome(repayCollectVo.getCollectInterest(), repayCollectVo.getInvestUserId());
//
//            //处理投资人账户金额
//            DealAction receiveRepayAction = new ReceiveRepayCashDealAction();
//            receiveRepayAction.deal(repayCollectVo.getInvestUserId(),
//                    repayCollectVo.getCollectAmount().subtract(repayCollectVo.getAdditionalRateAmount()),
//                    item.getItemName() + "项目回款本息");
//            count = dealModule.dealAction(receiveRepayAction);
//            if (count < 1) {
//                throw new CrowdException("update_error");
//            }
//            //插入资金明细记录
//            OperateAction operate = new IncomeOperateAction();
//            operate.operateAction(itemRepay.getOrderNo(), OperateContants.INVESTORS_PAYMENT,itemId,
//                    item.getItemName(),itemRepay.getRepayAmount());
//            operateModule.operateAction(operate);
//        }
//
//        boolean isPayoff = false;
//        if (itemRepay.getRepayCurrentPeriod().intValue() == itemRepay.getRepayTotalPeriod().intValue()) {
//            isPayoff = !isPayoff;
//        }
//
//        //更新还款状态
//        Map param = new HashMap();
//        param.put("newStatus",2);
//        param.put("oldStatus",1);
//        param.put("id",itemRepay.getId());
//        repayMapper.updateRepayByStatusAndId(param);
//
//        //更新标账户余额
//        count = itemMapper.updateUsableById(item.getUsable(),repayAmount.negate(),itemId);
//        if(count < 1){
//            throw new CrowdException("update_error");
//        }
//
//        //插入还款订单表
//        String orderNo = StringUtils.getOrderNo();
//        BusRepayOrder repayOrder = new BusRepayOrder();
//        repayOrder.setAddip(IpUtils.get());
//        repayOrder.setAddtime(new Date());
//        repayOrder.setRepayAmount(itemRepay.getRepayAmount());
//        repayOrder.setRepayId(itemRepay.getId());
//        repayOrder.setRepayOrder(orderNo);
//        repayOrder.setRepayType(2);
//        repayOrder.setItemId(itemId);
//        repayOrder.setRepayPeriod(currentPeriod);
//        repayOrderMapper.insert(repayOrder);
//
//        //请求恒丰
//        HfBidRepayVo repayVo = new HfBidRepayVo();
//        repayVo.setBidId(itemId + "");
//        repayVo.setTotalAmount(repayAmount);
//        repayVo.setTotalNum(itemCollects.size());
//        repayVo.setOrderId(orderNo);
//        repayVo.setRepayStatus(5);
//        repayVo.setPayoff(isPayoff);
//
//	    HfResultBean result = investApi.bidRepay(repayVo, itemCollects);// 请求恒丰
//	    return Message.OK;
//    }

    private Map addIncome(BigDecimal incomeAmount, Integer userId) {
        //向income中插入一条数据
        BusIncome busIncome = new BusIncome();
        busIncome.setIncomeAmout(incomeAmount);
        busIncome.setUserId(userId);
        busIncome.setIncomeType(2);
        Date date = new Date();
        busIncome.setAddtime(date);
        SimpleDateFormat incomeDate = new SimpleDateFormat("yyyyMMdd");
        busIncome.setIncomeDate(incomeDate.format(date));
        incomeMapper.insert(busIncome);

        //向income_stat表中修改待收和已收收益
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", userId);
        param.put("waitIncome", BigDecimal.ZERO.subtract(incomeAmount));
        param.put("earnedIncome", incomeAmount);
        param.put("totalIncome", 0);
        int count = incomeStatMapper.updateByWaitEarned(param);
        if (count < 1) {
            throw new CrowdException("update_error");
        }
        return Message.OK;
    }
}
